package com.example.personalblog.controller;

import com.example.personalblog.entity.Comment;
import com.example.personalblog.service.ArticleService;
import com.example.personalblog.service.CommentService;
import com.example.personalblog.service.UserService;
import com.example.personalblog.utils.DataTimeUtil;
import com.example.personalblog.vo.ShowBlog;
import com.example.personalblog.vo.ShowComment;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class BlogController {

    @Autowired
    ArticleService articleService;

    @Autowired
    UserService userService;

    @Autowired
    CommentService commentService;


    @GetMapping("/blog/{id}")
    public String getBlog(@PathVariable int id, Model model){

        ShowBlog blog = articleService.findBlog(id);
        List<ShowComment> commentList = commentService.findCommentByBlogId(blog.getId());

        model.addAttribute("blog",blog);
        model.addAttribute("commentList",commentList);

        return "/blog";
    }

    @PostMapping("/comment")
    public String comment(Model model, Comment comment){
        int uid = userService.findUser((String) SecurityUtils.getSubject().getPrincipal()).getId();

        comment.setUid(uid);
        comment.setState(0);
        comment.setCommentTime(DataTimeUtil.getDataTime());
        commentService.save(comment);

        List<ShowComment> commentList = commentService.findCommentByBlogId(comment.getAid());
        model.addAttribute("commentList",commentList);

        return "blog::commentList";

    }

}
